package com.wwwarehouse.resource_center.fragment.createobject.creategoods;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.activity.media.SelectImageActivity;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.customView.AutoClickButton;
import com.wwwarehouse.resource_center.eventbus_event.ImagePathEvent;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;

import java.io.File;
import java.util.List;

import de.greenrobot.event.EventBus;

import static android.app.Activity.RESULT_OK;

/**
 * Description:
 * Copyright  : Copyright (c) 2017
 * Author     : yfwang
 * Date       : 2017/9/25 16:24
 */
public class UploadPicFragment extends TheParentFragment implements PermissionUtils.PermissionCallbacks, View.OnClickListener, EasyPopupWindow.ChildClickListener {

    private LinearLayout mLLUpload;
    private LinearLayout mLLShowPic;
    private ImageView mPicIcon;
    private ImageView mPic;
    private AutoClickButton mConfirm;
    private EasyPopupWindow mEasyPopupWindow;
    private static int GALLERY = 99;
    private FileUtils mFileUtils;
    private File mFile;
    private static final int REQUEST_UPLOAD_IMAGE_CAMERA = 1;
    public static final String KEY_SELECT_IMAGE_PATH = "key_select_image_path";
    private String path;


    @Override
    protected int getContentId() {
        return R.layout.fragment_upload_pic;
    }

    @Override
    protected void init(View view) {
        mLLUpload = (LinearLayout) view.findViewById(R.id.ll_upload);
        mLLShowPic = (LinearLayout) view.findViewById(R.id.ll_show_pic);
        mPicIcon = (ImageView) view.findViewById(R.id.iv_pic_icon);
        mPic = (ImageView) view.findViewById(R.id.iv_pic);
        mConfirm = (AutoClickButton) view.findViewById(R.id.confirm_btn);
        mFileUtils = new FileUtils();

        Bundle bundle = getArguments();
        path = bundle.getString("path");
        if (path != null && !path.isEmpty()) {
            mLLUpload.setVisibility(View.GONE);
            mLLShowPic.setVisibility(View.VISIBLE);
            mPicIcon.setVisibility(View.GONE);
            if (path.startsWith("http")){
                ImageLoader.getInstance().displayImage( path, mPic);
            }else {
                ImageLoader.getInstance().displayImage("file://" + path, mPic);
            }
            mConfirm.setEnabled(true);
        }


        mLLUpload.setOnClickListener(this);
        mPic.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {

    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> permissionList) {
        //当requestCode相同时候，permissions.size == 请求的权限数时候，认为权限请求成功
        if (requestCode == 1 && permissionList.size() == 2) {
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            // 根据文件地址创建文件
            mFile = mFileUtils.getImagesFile("IMG_" + DateUtil.formatDate(System.currentTimeMillis(), "yyyyMMdd_HHmmss") + ".jpg");
            Uri uri;

            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + BuildConfig.ProviderSuffix, mFile);
            } else {
                // 把文件地址转换成Uri格式
                uri = Uri.fromFile(mFile);
            }

            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE_CAMERA);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> permissionList) {
        //调用了一次拒绝权限认为失败
        ToastUtils.showToast("拒绝了权限" + permissionList.get(0));
        PermissionUtils.permissionDialog(getActivity(), permissionList, null);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_upload) {
            mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.upload_image_popupwindow, getContext(), getActivity().findViewById(android.R.id.content), true, UploadPicFragment.this);

        } else if (id == R.id.iv_pic) {

            mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.upload_image_popupwindow, getContext(), getActivity().findViewById(android.R.id.content), true, UploadPicFragment.this);


        } else if (id == R.id.confirm_btn) {
            EventBus.getDefault().post(new ImagePathEvent(path, mFile));
            popFragment();
        } else if (id == R.id.btn_take_photo) {
            Constant.isTakePhotoFinished = false;
            PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else if (id == R.id.btn_gallery) {
            startActivityForResult(new Intent(getActivity(), SelectImageActivity.class), GALLERY);
        } else if (id == R.id.btn_cancel) {
            if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
                mEasyPopupWindow.dismiss();
            }

        }


    }

    @Override
    public void onResume() {
        super.onResume();
        Constant.isTakePhotoFinished = true;
    }

    @Override
    public void getChildView(int i, View view) {
        Button take = (Button) view.findViewById(R.id.btn_take_photo);
        Button gallery = (Button) view.findViewById(R.id.btn_gallery);
        Button cancel = (Button) view.findViewById(R.id.btn_cancel);

        take.setOnClickListener(this);
        gallery.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == GALLERY && resultCode == RESULT_OK) {
            //单选
            path = data.getStringExtra(KEY_SELECT_IMAGE_PATH);

        } else if (requestCode == REQUEST_UPLOAD_IMAGE_CAMERA && resultCode == RESULT_OK) {
            //拍照
            path = mFile.getAbsolutePath();
        }
        if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
            mEasyPopupWindow.dismiss();
        }
        mLLUpload.setVisibility(View.GONE);
        mLLShowPic.setVisibility(View.VISIBLE);
        if (path != null && !path.isEmpty()) {
            mPicIcon.setVisibility(View.GONE);
            ImageLoader.getInstance().displayImage("file://" + path, mPic);
            mConfirm.setEnabled(true);
        } else {
            mPicIcon.setVisibility(View.VISIBLE);
            mConfirm.setEnabled(false);

        }
    }
}
